package part14语言包.object类;

import javax.sound.midi.Soundbank;

public class Clone深克隆 {
	public static void main(String[] args) throws CloneNotSupportedException {
		// 创建一个Bod类的对象
		Boy2 boy = new Boy2();
		boy.setName("晨宇");
			
		// 创建一个Girl类的对象
		Girl2 girl = new Girl2();
		girl.setName("baby");
		// 设置女朋友属性
		boy.setGirl(girl);
				
		// 输出boy的信息
		System.out.println(boy.toString());
		System.out.println("原生：" +  boy.hashCode() + ",gril对象：" +  boy.getGirl().hashCode());
		
		// 克隆
		Boy2 boy2 = (Boy2) boy.clone();
		boy2.setName("YY");
		boy2.getGirl().setName("冰冰");
		// 输出克隆boy2的信息
		System.out.println(boy2.toString());
		System.out.println("克隆：" +  boy2.hashCode() + ",gril对象：" +  boy2.getGirl().hashCode());
		
		System.out.println("原生：" +  boy.toString());
		System.out.println("原生：" + boy.hashCode() + ",gril对象：" +  boy.getGirl().hashCode());
	}

}
class Boy2 implements Cloneable{
	private String name;
	private Girl2 girl; // 对象属性
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Girl2 getGirl() {
		return girl;
	}
	public void setGirl(Girl2 girl) {
		this.girl = girl;
	}
	@Override
	public String toString() {
		return "Boy2 [name=" + name + ", girl=" + girl + "]";
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {
		// 实现深克隆 克隆boy的时候同时克隆girl
		
		// 1 克隆出一个Boy对象
		Boy2 boy = (Boy2) super.clone();
		// 2 克隆出一个Girl对象给克隆的boy
		Girl2 girl = (Girl2) boy.getGirl().clone();
		// 3 赋值给boy对象
		boy.setGirl(girl);
	
		return boy;
	}
}

class Girl2 implements Cloneable{ // 必须实现Cloneable接口，重写clone()方法
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Girl2 [name=" + name + "]";
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {

		return super.clone();
	}
}
